import { Service } from 'egg';
import { Browse } from '../model/Browse';
import * as moment from 'moment';

class BrowseService extends Service {
    /**
     * 计算浏览时间
     * @param user_id 
     */
    public async computeBrowseTime(user_id: string) {
        await this.dealWithBrowseTime(user_id);
    }

    /**
     * 处理浏览时间
     */
    public async dealWithBrowseTime(user_id: string) {
        const resultBrowse = await this.ctx.model.Browse.findOne<Browse>({ attributes: ['browse_id'], where: { user_id, browse_status: '1' } });
        const dateStr = moment().format('YYYY-MM-DD HH:mm:ss');
        if (!resultBrowse) {
            await this.ctx.model.Browse.findOrCreate({ where: { user_id: user_id, browse_status: '1' }, defaults: { browse_id: this.ctx.helper.genUUID(), browse_timestamp: dateStr, browse_time: 0, is_delete: '1' } }).spread((submitData, created) => {
                if (created === false) {
                    console.log(submitData);
                }
            })
            await this.ctx.model.User.update({ is_online: '1', is_news: '2' }, { where: { user_id } });
        } else {
            const browse_id = resultBrowse['browse_id'];
            await this.ctx.model.Browse.update({ browse_timestamp: dateStr }, { where: { browse_id } });
        }
    }

    /**
     * 获取每日首次点击量
     * @param param 
     */
    public async getClickNum(param: any) {
        const resultDate: any = await this.ctx.helper.getFullData(param.startTime, param.endTime);
        const startTime = param.startTime + ' 00:00:00';
        const endTime = param.endTime + ' 23:59:59';
        const queryStr = `SELECT date ,COUNT( * ) as total FROM ( SELECT DATE_FORMAT( created_at, '%Y-%m-%d' )`
            + ` as date, COUNT( * ) FROM t_browse WHERE created_at BETWEEN :startTime AND`
            + ` :endTime GROUP BY DATE_FORMAT( created_at, '%Y-%m-%d' ), user_id ) temp GROUP BY date`;
        const resultActivity = await this.ctx.model.query(
            queryStr,
            {
                type: this.ctx.app.Sequelize.QueryTypes.SELECT,
                replacements: { startTime, endTime }
            }
        )
        if (resultActivity.length <= 0) {
            return resultDate;
        }
        for (let i = 0; i < resultActivity.length; i++) {
            for (let j = 0; j < resultDate.length; j++) {
                if (resultActivity[i].date === resultDate[j].date) {
                    resultDate[j].total = resultActivity[i].total;
                }
            }
        }
        return resultDate;
    }

    /**
     * 获取用户日浏览平均时间
     * @param param 
     */
    public async getBrowseTime(param: any) {
        const resultDate: any = await this.ctx.helper.getFullData(param.startTime, param.endTime);
        const startTime = param.startTime + ' 00:00:00';
        const endTime = param.endTime + ' 23:59:59';
        const queryStr = `SELECT date ,AVG( time ) as total FROM ( SELECT DATE_FORMAT( created_at, '%Y-%m-%d' )`
            + ` as date, SUM( browse_time ) as time FROM t_browse WHERE created_at BETWEEN :startTime AND`
            + ` :endTime GROUP BY DATE_FORMAT( created_at, '%Y-%m-%d' ), user_id ) as temp GROUP BY date`;
        const resultActivity = await this.ctx.model.query(
            queryStr,
            {
                type: this.ctx.app.Sequelize.QueryTypes.SELECT,
                replacements: { startTime, endTime }
            }
        )
        if (resultActivity.length <= 0) {
            return resultDate;
        }
        for (let i = 0; i < resultActivity.length; i++) {
            for (let j = 0; j < resultDate.length; j++) {
                if (resultActivity[i].date === resultDate[j].date) {
                    resultDate[j].total = resultActivity[i].total;
                }
            }
        }
        return resultDate;
    }
}
export default BrowseService;